package com.ct.gd.passport.view.weather.util;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.util.Log;

import com.ct.gd.passport.view.weather.WeatherCondition;

/**
 * 获取天气工具类
 * 
 * @author Administrator
 * 
 */
public class WeatherFacade {

	/**
	 * 通过新浪天气api获取某个城市某天的天气情况
	 * 
	 * @param city
	 *            城市，必须是中文
	 * @param day
	 *            第几天，0表示今天
	 * @return
	 */
	public static final WeatherCondition getSinaWeather(String city, int day) {

		try {
			HttpClient client = new DefaultHttpClient();
			city = URLEncoder.encode(city, "gb2312");	// 不能用utf-8
			StringBuffer urlBuf = new StringBuffer();
			urlBuf.append(ConstData.SINA_WEATHER_URL).append("?password=").append(ConstData.SINA_API_KEY).append("&day=").append(day)
					.append("&city=").append(city);
			HttpGet request = new HttpGet(urlBuf.toString());

			Log.i("search", urlBuf.toString());
			XMLReader xr = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
			SinaWeatherHandler swh = new SinaWeatherHandler();
			xr.setContentHandler(swh);

			Log.i("search", "send");
			HttpResponse response = client.execute(request);
			InputStreamReader isr = new InputStreamReader(response.getEntity().getContent(), "utf-8");
			xr.parse(new InputSource(isr));

			Log.i("search", "response");
			WeatherCondition wc = swh.getWeatherCondition();
			if(wc.city != null){
				return wc;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

}
